package client;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * @file Client_Response.java
 *
 * @version 0.3
 * @author James Dibble 10009689
 * 
 * Latest Source:
 * http://code.google.com/p/csp-server/source/browse/
 *                                  trunk/Server/src/client/Client_Response.java
 */
public class Client_Response extends Thread {
    // <editor-fold defaultstate="collapsed" desc="Attributes">
    private Socket sSocket;
    private PrintWriter pwServerOutput;
    private Scanner scnrInput = new Scanner(System.in);
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="Constructors">
    /**
     * Create an object to send messages to the server.
     * 
     * @param socket
     * @throws IOException 
     */
    public Client_Response(Socket socket) throws IOException {
        this.sSocket = socket;
        pwServerOutput = new PrintWriter(socket.getOutputStream(), true);
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="Methods">
    @Override
    public void run() {
        //Loop until the client disconnects.  
        //TODO Change this to non blocking.  At present the user has to press
        //\r again after the client has disconnected.
        //Issue http://code.google.com/p/csp-server/issues/detail?id=2&can=1
        while (sSocket != null) {
            this.SendToServer(scnrInput.nextLine());
        }
    }

    /**
     * Transmit a textual message to the server.
     * 
     * @param strMessage 
     */
    public void SendToServer(String strMessage) {
        pwServerOutput.println(strMessage);
    }
    
    /**
     * Close all connections to the server on the Client's socket.
     * 
     * @throws IOException 
     */
    public void Disconnect() throws IOException{
        this.sSocket.close();
        this.sSocket = null;
    }
    // </editor-fold>
}
